<template>
    <div id="product">
        {{list}}
        <div class="product_top">
            <el-button type="primary" @click='addProduct'>添加</el-button>
            <el-input v-model="input" placeholder="请输入产品名称"></el-input>
            <el-button type="primary" @click='search'>查询</el-button>
        </div>
        <div class="product_center">
            <el-table
            :data="productList"
            stripe
            style="width: 100%">
            <el-table-column
            prop="id"
            label="编号"
            width="180">
            </el-table-column>
            <el-table-column
            prop="name"
            label="产品名称"
            width="180">
            </el-table-column>
            <el-table-column
            prop="price"
            label="价格"
            width="180">
            </el-table-column>
            <el-table-column
            prop="description"
            label="产品描述"
            width="180">
            </el-table-column>
            <el-table-column
            prop="categoryName"
            label="所属产品"
            width="180">
            </el-table-column>
            <el-table-column
            label="操作">
                <template slot-scope='scope'>
                    <!-- <a @click="deleteById(scope.$index,scope.row)">删除</a> &nbsp;&nbsp; -->
                    <!-- <a @click='change(scope.row)'>编辑</a> &nbsp;&nbsp; -->
                    <!-- <a @click='details(scope.row.id)'>详情</a> -->
                    <el-button type="text" @click="deleteById(scope.$index,scope.row)">删除</el-button>&nbsp;&nbsp;
                    <el-button type="text" @click='change(scope.row)'>编辑</el-button>&nbsp;&nbsp;
                    <el-button type="text" @click='details(scope.row.id)'>详情</el-button>
                </template>
                
            </el-table-column>
        </el-table>
        </div>
        <div class="product_footer">
             <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage1"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="total">
            </el-pagination>
        </div>
        <!-- 添加/修改模态框 -->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref='myform'>
                <el-form-item label="产品名称" :label-width="formLabelWidth" prop='name'>
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                 <el-form-item label="产品价格" :label-width="formLabelWidth" prop='price'>
                    <el-input v-model.number="form.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所属栏目" :label-width="formLabelWidth" prop='categoryId'>
                    <el-select v-model="form.categoryId" placeholder="请选择活动区域">
                        <el-option :label="item.name" :value="item.id" v-for="item in categorys" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品介绍" :label-width="formLabelWidth">
                    <el-input type="textarea" v-model="form.description"></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth">
                    <el-button type="primary">点击上传</el-button>
                    <br>
                    <span>只能上传png格式，大小不超过500kb</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('myform')">确 定</el-button>
            </div>
         </el-dialog>
    </div>
</template>
<script>
import qs from 'querystring';
export default {
    data(){
        return {
            input:"",
            products:[],
            currentPage1:1,
            currentPage2:0,
            total:0,
            pageSize:10,
            title:"添加产品信息",
            categorys:[],//素有栏目信息
            dialogFormVisible: false,
            form: {
                name: '',
                price: '',
                categoryId: '',
                description:''
            },


            formLabelWidth: '120px',
            rules: {
                    name: [
                        { required: true, message: '请输入产品名称', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ],
                    price:[
                        { required: true, message: '价格不能为空'},
                        { type: 'number', message: '价格必须为数字值'}
                    ],
                    categoryId: [
                        { required: true, message: '请选择所属栏目', trigger: 'change' }
                    ]
                    
                    }
        //rules end
        }
    },
    computed:{
        list(){
            return this.$store.getters.list;
        },
        productList:function(){
            var self=this;
           // var filterList=[];
            //1.获取所有产品信息
           // console.log(this.products);
            //2.获取所有栏目信息
           // console.log(this.categorys);
            //3.用一个产品的id匹配所有栏目id，找到相同id对象，将栏目对象中的name赋值给产品对象
            this.products.forEach((item)=>{
                //item->产品对象 item.categoryId
                for(var i=0;i<self.categorys.length;i++){
                    //categorys[i]:每一个栏目对象
                        if(item.categoryId==self.categorys[i].id){
                            //console.log(self.categorys[i]);
                            item.categoryName=self.categorys[i].name;
                           // filterList.push(item);
                        }
                }

            })
            return this.products
        }   
    },
    methods: {
    //给详情按钮绑定事件
    details(id){
        //alert(id);
        this.$router.push({path:"/details/index",query:{id:id}});
    },
    //给确定按钮绑定事件
    submitForm(formName){
        var self=this;
        //1.获取表单数据+表单验证
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //alert('submit!');
            self.$axios.post("/product/saveOrUpdate",qs.stringify(self.form)).then(response=>{
                if(response.data.status==200){
                    //保存成功
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    });
                     self.findAll();

                    
                }else{
                    //保存失败
                    this.$message.error('保存失败');
                }
                self.dialogFormVisible=false;
            })
             //2.发送请求

          } else {
            console.log('error submit!!');
            return false;
          }
        });
        
       
    },
    //添加按钮绑定事件
    addProduct(){
        this.dialogFormVisible=true;
        this.title="添加产品信息";
        this.form={
            name: '',
            price: '',
            categoryId:'',
            description:''
        }

    },
    //编辑按钮绑定事件
    change(row){
        this.dialogFormVisible=true;
        this.title="修改产品信息";
        this.form={
            id:row.id,
            name: row.name,
            price: row.price,
            categoryId: row.categoryId,
            description:row.description
        }
    },
    //点击搜索按钮，触发搜索函数
    search(){
        //1.获取用户输入
       // alert(this.input);
        if(this.input){
            this.findAll(this.input);
        }else{
            this.findAll();
        }
       
    },
    //封装查询所有栏目函数
    findAllCategorys(){
        return this.$axios.get("/category/findAll")
    },
    //根据id单个删除
    deleteById(index,row){
        var self=this;
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            //用户确认删除
            var id=row.id;
            self.$axios.get("/product/deleteById",{
                params:{
                    id
                }
            }).then((response)=>{
                if(response.data.status==200){
                    //删除成功
                     this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    self.findAll();
                }else{
                    //删除失败
                    this.$message.error('删除失败');
                }
            })
         /*  this.$message({
            type: 'success',
            message: '删除成功!'
          }); */
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
       
    },
    //分页查询封装函数
    findAll(name){
        if(name){
            //点击搜索
             var data={
                page:this.currentPage2,
                pageSize:this.pageSize,
                name:name
            }
        }else{
            //非搜索
             var data={
                page:this.currentPage2,
                pageSize:this.pageSize
            }
        }
       
            //alert(qs.stringify(data));
            this.$axios.post("/product/query",qs.stringify(data)).then(response=>{
            this.products=response.data.data.list;
            this.total=response.data.data.total;

            })
    },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
          //根据分页发送请求
         // console.log(val);
          this.currentPage1=val;
          this.currentPage2=val-1;

          this.findAll();
         
      }
    },
    created(){
        //通过状态机获取数据
        this.$store.dispatch("getall");

        //
        this.findAllCategorys().then(response=>{
            //所有栏目查询完成
            this.categorys=response.data.data;
             this.findAll();//查询所有产品
        })
       
        
        
    }
}
</script>
<style lang="scss" scoped>
    #product{
        padding:20px;
        .product_top .el-input{
            width:25%;
            margin:0 10px 0 20px
        }
    }
</style>